<?php
/**
Version 0.1
SEMF - Web Desiging Framework for Sport Event Managment
Copyright (C) 2006, SEMF Developers

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
function savePageXML($new_doc, $page_xml)
{
	$backup_dirname = "/backup/";
	$backup_postfix = ".bk";
	$ver_postfix = ".ver";
	$meta_postfix = ".meta";
	$ver_limit = 50;
	
	$min = -1;
	if(file_exists($page_xml)) //the backups done only if the file exists..
	{
		$path_name = dirname($page_xml);
		$file_name = basename($page_xml);
		
		if(!is_dir($path_name))
		{
			mkdir($path_name);
		}
		$backup_dir = $path_name.$backup_dirname;
		if(!is_dir($backup_dir))
		{
			mkdir($backup_dir);
		}
		
		$page_xml_bk = $backup_dir.$file_name.$backup_postfix;
		$new_doc->save($page_xml_bk);
		
		//read the current version..
		$meta_filename = $backup_dir.$file_name.$meta_postfix;
		if(file_exists($meta_filename))
		{
			$filesize = filesize($meta_filename);
		}
		else
		{
			$filesize = 0;
		}
		
		$undoed = false;
		$redoed = false;
		
		if($filesize > 0)
		{
			$meta_file = fopen($meta_filename, "r");
			$contents = fread($meta_file, $filesize);
			$sep = strpos($contents, ",");
			$current = substr($contents, 0, $sep);
			$rest = substr($contents, $sep+1);
			$sep = strpos($rest, ",");
			$max = substr($rest, 0, $sep);
			$min = substr($rest, $sep + 1);
			
			if($min != -1)
			{
				if($min != $current)
				{
					$undoed = true;
				}
			}
			
			fclose($meta_file);
			unlink($meta_filename);
		}
		else
		{
			$current = -1;
			$min = -1;
		}
		
		if($current == $ver_limit)
		{ 
			$current = 0;
			//the first time it go through that..
			$min = 0;
		}
		else
		{
			$current ++;
		}
		
		$max = $current;
		if($min != -1)
		{
			if(!$undoed)
			{
				$min = $current;
			}
		}
		
		
		$page_xml_ver = $backup_dir.$file_name.$ver_postfix.$current;
		
		
		
		$meta_file = fopen($meta_filename, "w");
		fwrite($meta_file, $current.",".$max.",".$min);
		fclose($meta_file);
		
		$new_doc->save($page_xml_ver);
		
		/** until the xdiff is ready, need to keep the same old version */
		//xdiff_file_diff($old_version, $new_version, $diff_filename);
	}
	$new_doc->save($page_xml);
}
?>